import 'dart:developer';

import 'package:FlutterDemo/bean/beans_factory.dart';
import 'package:flutter/material.dart';

Widget buildSampleList() {
  return ListView(
    children: [
      ListTile(
        title: Text("aaa"),
      ),
      ListTile(
        title: Text("bbb"),
      ),
      ListTile(
        title: Text("ccc"),
      ),
      ListTile(
        title: Text("ddd"),
      ),
      ListTile(
        title: Text("eee"),
      ),
    ],
  );
}

/// 示例列表：自定义条目
buildSampleListByListItems() {
  return ListView(
    children: buildListItems(),
  );
}

/// 使用于listview
buildListItems() {
  List<Widget> list = [];
  for (var i = 0; i < 25; i++) {
    list.add(_SampleListItem(title: "sample $i"));
  }
  return list;
}

/// 异步创建数据
Future<List<Widget>> buildListItemsAsync() async {
  await new Future.delayed(const Duration(seconds: 1));

  List<Widget> list = [];
  for (var i = 0; i < 25; i++) {
    list.add(_SampleListItem(title: "sample $i"));
  }
  return list;
}

/// 动态创建数据
Widget buildSampleListBuilder() {
  return ListView.builder(
    itemBuilder: (context, index) {
      return ListTile(
        title: Text("sample $index"),
      );
    },
    itemCount: 20,
    itemExtent: 50,
  );
}

/// 横向滚动
Widget buildSampleHorizontalListView() {
  return Container(
    height: 200,
    child: ListView(
      scrollDirection: Axis.horizontal,
      children: [
        Container(
          width: 180.0,
          color: Colors.lightBlue,
        ),
        Container(
          width: 180.0,
          color: Colors.amber,
        ),
        Container(
          width: 180.0,
          color: Colors.deepOrange,
        ),
        Container(
          width: 180.0,
          color: Colors.deepOrangeAccent,
        )
      ],
    ),
  );
}

/// List 图片轮播
buildListPicBinner() {
  var imgList = BeansFactory.instance.buildSampleListUrls();
  return Container(
    height: 200,
    child: ListView.builder(
      scrollDirection: Axis.horizontal,
      itemBuilder: (context, index) {
        return Image.network(imgList[index]);
      },
      itemCount: imgList.length,
    ),
  );
}

/// 分割线
Widget buildSampleListSeparated(List<Widget> list) {
  return ListView.separated(
    itemBuilder: (context, index) {
      // return list[index];
      // return buildCutstomerItem(list, index);
      return buildCustomerListText(list, index);
    },
    separatorBuilder: (context, index) {
      return Divider();
    },
    itemCount: list.length,
  );
}

/// 自定义的item
buildCustomerListText(List<Widget> list, int index) {
  var item = list[index] as _SampleListItem;
  return ListTile(
    title: Text(
      item.title,
      textAlign: TextAlign.center,
    ), // 控制标题居中
  );
}

/// 自定义的item
buildCutstomerItem(List<Widget> list, int index) {
  var item = list[index] as _SampleListItem;
  return Container(
    height: 45,
    alignment: Alignment.center,
    child: Text(item.title),
  );
}

/// 示例列表条目
class _SampleListItem extends StatelessWidget {
  final String title;

  const _SampleListItem({Key? key, required this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.fromLTRB(20, 10, 20, 10),
      child: Container(
        height: 85,
        alignment: Alignment.center,
        child: Text("$title"),
      ),
    );
  }
}

/// ScrollControll示例
class ScrollControllWidget extends StatefulWidget {
  const ScrollControllWidget({Key? key}) : super(key: key);

  @override
  _ScrollControllWidgetState createState() => _ScrollControllWidgetState();
}

class _ScrollControllWidgetState extends State<ScrollControllWidget> {
  // ListView的控制器，可以获取当前滚动位置，也可以滚动到指定的位置
  late ScrollController _controller;

  @override
  void initState() {
    super.initState();

    _controller = ScrollController()
      ..addListener(() {
        log("当前位置: ${_controller.position}");
      });
  }

  @override
  Widget build(BuildContext context) {
    // return buildSampleScrollController();
    return buildPraticeScrollController();
  }

  /// 构建标准的ScrollController 测试
  ListView buildSampleScrollController() {
    return ListView.builder(
      // physics: NeverScrollableScrollPhysics(), // 禁止滚动到顶部和滚动到底部
      physics: ClampingScrollPhysics(),
      // 包裹内容，不会有回弹
      controller: _controller,
      reverse: false,
      itemBuilder: (context, index) {
        return _SampleListItem(title: "$index");
      },
      itemCount: 30,
      itemExtent: 50,
    );
  }

  /// 构建复杂的测试
  Widget buildPraticeScrollController() {
    return Column(
      children: [
        Container(
          child: RaisedButton(
            child: Text("滚动到指定位置"),
            onPressed: () {
              // _controller.animateTo(200,  /// 滚动到指定像素
              //     duration: Duration(microseconds: 300), curve: Curves.linear);
            },
          ),
        ),
        Expanded(child: buildSampleScrollController()) // 使用剩下空间
      ],
    );
  }
}

/// 滚动到指定位置 https://www.jianshu.com/p/443f1aef488f
class SampleScrollControll2TargetPos extends StatefulWidget {
  const SampleScrollControll2TargetPos({Key? key}) : super(key: key);

  @override
  _SampleScrollControll2TargetPosState createState() => _SampleScrollControll2TargetPosState();
}

// 默认高度
const double ITEM_HEIGHT = 100.0;

class _SampleScrollControll2TargetPosState extends State<SampleScrollControll2TargetPos> {
  List<ItemWrapper> list = [];

  // ScrollController scrollController= ScrollController();
  late ScrollController scrollController;

  @override
  void initState() {
    super.initState();
    scrollController = ScrollController();
    scrollController.addListener(() {
      log("pos: ${scrollController.position}");
    });

    BeansFactory.instance.buildScrollControllerListData().then((value) {
      log("数据发生了变化");
      setState(() {
        list.addAll(value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly, // 水平均分
          children: [
            FlatButton(
              onPressed: _scrollToKd,
              child: Text("杜兰特"),
              textColor: Colors.blueGrey,
              color: Colors.deepOrangeAccent,
            ),
            FlatButton(
              onPressed: _scrollToKobe,
              child: Text("科比"),
              textColor: Colors.blueGrey,
              color: Colors.deepOrangeAccent,
            )
          ],
        ),
        Expanded(child: buildListView())
      ],
    );
  }

  buildListView() {
    return ListView.builder(
      scrollDirection: Axis.vertical,
      controller: scrollController,
      // 控制器添加
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return makeSampleItem(context, index);
      },
      itemCount: list.length,
    );
  }

  makeSampleItem(BuildContext context, int index) {
    return Container(
      height: ITEM_HEIGHT,
      margin: EdgeInsets.only(top: 12, left: 20, right: 20),
      child: Container(
        padding: const EdgeInsets.all(2.0),
        alignment: Alignment.center,
        color: Color(0x33000000),
        child: Text(list[index].displayName),
      ),
    );
  }

  /// 滚动到指定位置
  _scroll2Position() {
    log("_scroll2Position");
    for (int i = 0; i < list.length; i++) {
      var isSelected = list[i].selected;
      if (isSelected) {
        log("跳转到: ${list[i].displayName}");
        // 滚动到指定位置
        scrollController.animateTo(i * ITEM_HEIGHT, duration: Duration(milliseconds: 300), curve: Curves.ease);
        break;
      }
    }
  }

  _scrollToKobe() {
    log("_scrollToKobe");
    setState(() {
      list.forEach((element) {
        var name = element.displayName;
        log("_scrollToKobe name = $name");
        if (name == "科比") {
          log("需要更新");
          element.selected = true;
        } else {
          log("不需要更新");
          element.selected = false;
        }
      });
      // 滚动到指定位置
      _scroll2Position();
    });
  }

  _scrollToKd() {
    log("_scrollToKd");
    setState(() {
      list.forEach((element) {
        var name = element.displayName;
        log("_scrollToKd name = $name");
        if (name == "杜兰特") {
          log("需要更新");
          element.selected = true;
        } else {
          log("不需要更新");
          element.selected = false;
        }
      });
      // 滚动到指定位置
      _scroll2Position();
    });
  }
}
